package com.brillilab.service.module.netease;

import com.alibaba.fastjson.JSONObject;
import com.brillilab.service.utils.CheckSumUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.URLDecoder;
import java.util.*;


@Slf4j
@Component
@SuppressWarnings("deprecation")
public class NeteaseApiHelper {

	@Value("${netease.im.appKey}")
	private String appKey;

	@Value("${netease.im.appSecret}")
	private String appSecret;

	/**
	 * 网易云信请求
	 * 
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("resource")
	public JSONObject api(String apiUrl, Map<String,String> paramMap) throws Exception {
		JSONObject jsonResult = null;

		// String apiUrl =
		// "https://api.netease.im/nimserver/user/create.action";
		apiUrl = URLDecoder.decode(apiUrl, "UTF-8");
		HttpPost httpPost = new HttpPost(apiUrl);
		String nonce = getNonce();
		String curTime = getCurTime();
		String checkSum = CheckSumUtil.getCheckSum(appSecret, nonce, curTime);

		// 设置请求的header
		httpPost.addHeader("AppKey", appKey);
		httpPost.addHeader("Nonce", nonce);
		httpPost.addHeader("CurTime", curTime);
		httpPost.addHeader("CheckSum", checkSum);
		httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

//		// 解决中文乱码问题
//		StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
//		httpPost.setEntity(entity);

		// 设置请求的参数
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		Set<String> keySet = paramMap.keySet();
	    for (String key : keySet) {
	    	nvps.add(new BasicNameValuePair(key, paramMap.get(key)));
		}
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        
		// 执行请求
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpResponse response = httpClient.execute(httpPost);
		// 请求发送成功，并得到响应
		if (response.getStatusLine().getStatusCode() == 200) {
			// 读取服务器返回过来的json字符串数据
			String strResult = EntityUtils.toString(response.getEntity(), "utf-8");
			// 把json字符串转换成json对象
			jsonResult = JSONObject.parseObject(strResult);
		} else {
			log.error(">>>>>>>  网易云信POST请求提交失败得到响应:{}", response.getStatusLine().getStatusCode());
		}
		return jsonResult;
	}

	/**
	 * @return 开发者平台分配的appkey
	 */
	public String getAppKey() {
		return appKey;
	}

	/**
	 * @Methods getAppSecret
	 * 
	 * @return String
	 * 
	 * @Description 开发者平台分配的AppSecret
	 */
	public String getAppSecret() {
		return appSecret;
	}

	/**
	 * 随机数（最大长度128个字符）
	 * 
	 * @return
	 */
	public String getNonce() {
		return String.valueOf(RandomUtils.nextLong());
	}

	/**
	 * 当前UTC时间戳，从1970年1月1日0点0 分0 秒开始到现在的秒数(String)
	 */
	public String getCurTime() {
		return String.valueOf((new Date()).getTime() / 1000L);
	}

	/**
	 * @param appSecret
	 * @param nonce
	 * @param curTime
	 * @return SHA1(AppSecret + Nonce +
	 *         CurTime),三个参数拼接的字符串，进行SHA1哈希计算，转化成16进制字符(String，小写)
	 */
	public String getCheckSum(String appSecret, String nonce, String curTime) {
		return DigestUtils.sha1Hex(appSecret + nonce + curTime);
	}

	public void setAppKey(String appKey) {
		this.appKey = appKey;
	}

	public void setAppSecret(String appSecret) {
		this.appSecret = appSecret;
	}

}
